<template>
  <div class="annotation-container" v-loading="loading">
    <!-- frabic版本为5.0.0才能展示图片 -->
    <annotation
      type="annotation"
      :annotationSourceData="annotationSourceData"
      ref="annotation"
      @save="handleSave"
      @preAnnotation="handlePreAnnotation"
    ></annotation>
    <el-dialog
      title="选择预标注模型："
      :visible.sync="dialogFormVisible"
      @close="afterDialogClose"
      width="500px"
    >
      <el-form ref="dialogForm" label-position="left">
        <div>请选择预标注该文件时依据的预标注模型：</div>
        <el-form-item label="预标注模型：" required>
          <el-select v-model="extractModelSelection" placeholder="请选择">
            <el-option
              v-for="item in extractModelList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="preAnnotationFormSubmit"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import annotation from '../components/annotation/index.vue';

export default {
  name: 'Annotation',
  components: {
    annotation,
  },
  data: () => {
    return {
      annotationSourceData: {
        relationList: [],
        ontologyMenu: [],
        ontologyList: [],
        content: '',
        record: {},
      },
      extractModelList: [], // 抽取模型列表
      dialogFormVisible: false,
      extractModelSelection: null,
      loading: false,
    };
  },
  computed: {},

  created() {
    this.getAnnotationSourceData();
    this.getExtractModel();
  },
  mounted() {},
  methods: {
    getExtractModel() {
      this.$api.knowledgeGeneration.getExtractModel().then((res) => {
        const { code, data, message } = res.data;
        if (code !== 200) {
          console.error(res);
          this.$message.error(message);
          return;
        }
        this.extractModelList = data.map((extractMode) => ({
          id: extractMode.id,
          title: extractMode.modelName,
        }));
      });
    },
    // 模态框关闭后
    afterDialogClose() {
      this.extractModelSelection = null;
    },
    getAnnotationSourceData() {
      this.loading = true;

      const {
        file_id = '',
        ontology_all_id = '',
        annotation_data_record_id = '',
      } = this.$route.query;

      const params = {
        file_id, //源数据id
        ontology_all_id, //选择的本体模型id
        annotation_data_record_id, //标注记录id:若此项为空,则表示是从【源数据管理】页面进入标注页的. 如果不为空则表示是从【标注数据】页面进入标注页的，目前此参数为空,有标注记录再完善
        user_id: '1', //当前用户id
      };

      this.$api.knowledgeGeneration
        .annotationSourceData(params)
        .then((res) => {
          if (res.data.code !== 200) {
            this.$message.error(res.data.message);
            setTimeout(() => {
              this.$router.go(-1);
            }, 2000);
            return;
          }
          this.setData(res.data.data);
          this.$refs.annotation.init();
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
        })
        .finally(() => {});
    },

    // 保存标注数据
    handleSave(data, onFinish) {
      const {
        file_id: fileId,
        ontology_all_id: ontologyModelId,
        annotation_data_record_id: recordId,
      } = this.$route.query;
      const params = {
        fileId, //源数据id
        ontologyModelId, //选择的本体模型id
        recordId: recordId ? recordId : '',
        userId: '1', //当前用户id
        ...data,
      };
      this.$api.knowledgeGeneration
        .saveOrUpdateAnnotation(params)
        .then((res) => {
          const { code, message } = res.data;
          if (code !== 200) {
            this.$message.warning(message);
            return;
          }
          this.$message.success(message);
          if (onFinish) {
            onFinish();
          }
        });
    },
    preAnnotationFormSubmit() {
      if (!this.extractModelSelection) {
        this.$message.warning('请选择预标注模型');
        this.dialogFormVisible = true;
        return;
      } else {
        this.handlePreAnnotation();
        this.dialogFormVisible = false;
      }
    },
    handlePreAnnotation() {
      if (!this.extractModelSelection) {
        this.dialogFormVisible = true;
        return;
      }
      this.loading = true;

      const {
        file_id = '',
        ontology_all_id = '',
        annotation_data_record_id = '',
      } = this.$route.query;

      const params = {
        recordId: annotation_data_record_id,
        ontologyAllId: ontology_all_id, //选择的本体模型id
        sourceDataFileId: file_id, //标注记录id:若此项为空,则表示是从【源数据管理】页面进入标注页的. 如果不为空则表示是从【标注数据】页面进入标注页的，目前此参数为空,有标注记录再完善
        extractModelId: this.extractModelSelection, // 抽取模型id
        user_id: '1', //当前用户id
      };
      this.$api.knowledgeGeneration
        .preAnnotation(params)
        .then((res) => {
          if (res.data.code !== 200) {
            this.$message.error(res.data.message);
            return;
          }
          this.setData(res.data.data);
          this.$refs.annotation.init();
        })
        .catch((err) => {
          console.log(err);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    setData(data) {
      this.annotationSourceData.relationList = data.relationList;
      this.annotationSourceData.ontologyMenu = data.ontologyMenu;

      const flattenChildren = (arr) =>
        arr.reduce((pre, next) => {
          const hasChild = (item) => item.children && item.children.length;
          if (hasChild(next)) {
            return pre.concat(flattenChildren(next.children), next);
          } else {
            return pre.concat(next);
          }
        }, []);
      this.annotationSourceData.ontologyList = flattenChildren(
        this.annotationSourceData.ontologyMenu
      );

      this.annotationSourceData.content = data.content
        .replaceAll('\n', '')
        .replaceAll('&lt;', '<')
        .replaceAll('&gt;', '>');
      this.annotationSourceData.record = data.record;
    },
  },
};
</script>
<style lang="scss" scoped>
.annotation-container {
  padding: 20px;
  background: #ffffff;
  border-radius: 4px;
}
</style>
